'use strict';

/**
 * @ngdoc service
 * @name jgappApp.DataByPage
 * @description
 * # DataByPage
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .service('DataByPage', function($http, Util, $filter) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        var DataByPage = function(url, options) {
            this.options = options || {};
            this.items = [];
            this.busy = false;
            this.limit = this.options.limit||10;
            this.start = 0;
            this.pageNo = 0;
            this.noData = true;
            this.url = url;
            this.nextPage();
            this.count = 0;
        };
        DataByPage.prototype.nextPage = function() {
            if (!this.noData) {
                return;
            }
            if (this.busy) {
                return;
            }
            this.start = (this.pageNo++) * this.limit;
            this.options.start = this.start
            this.options.limit = this.limit
            $http.get(this.url, {
                params: this.options
            }).
            success(function(data, status, headers, config) {
                if (data.logout) {
                    Util.logout();
                    return;
                }
                var items = data.dataList;
                if (items && items.length > 0) {
                    for (var i = 0; i < items.length; i++) {
                        this.items.push(items[i]);
                    }
                } else {
                    this.busy = true;
                }
            }.bind(this)).
            error(function(data, status, headers, config) {}.bind(this));
        };
        return DataByPage;

    });
